var http = require("http");
var fs = require('fs');
var mime = require('mime');
var server = http.createServer(handle);

function handle(req, res) {

  console.log(req.url);
  var filePath = "";

  if (req.url == "/") {

    filePath = __dirname + "/public/html/index.html";
  } else {

     filePath = __dirname + "/public" + req.url;
  }

  serverStatic(res, filePath);
}

function serverStatic(res, filePath) {

  fs.exists(filePath, function(exists) {

    if (exists) {

      fs.readFile(filePath, function(err, data) {

        if (err) {

          return;
        }

          res.writeHead(200, {"Content-Type":mime.lookup(filePath)});
          res.end(data);
        })
      } else {

          res.writeHead(404, {"Content-Type":"text/plain"});
          res.end("sorry, is not found");
      }
  })
}

server.listen(8080, function() {

  console.log("成功启动！");
})
